﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace Inspired.Euler
{
    public static class Problem059
    {
        /// <summary>
        /// Using a brute force attack, can you decrypt the cipher using XOR encryption?
        /// </summary>
        [EulerProblem(59, Title = "Using a brute force attack, can you decrypt the cipher using XOR encryption?")]
        public static long Solve()
        {
            Combinatorics.Variations<char> keys =
                new Combinatorics.Variations<char>(
                    Enumerable.Range('a', 26).Select(c => (char)c).ToList(), 3);
            char[] cipher =
                File.ReadAllText(@"..\..\Data\cipher1.txt")
                    .Split(",".ToCharArray())
                    .Select(number => (char)Convert.ToInt32(number))
                    //.Take(75)
                    .ToArray();

            foreach (var key in keys)
            {
                char[] decrypt =
                    cipher
                        .Select(
                            (character, index) =>
                            (char)(character ^ key[index % 3]))
                        .ToArray();

                string plain = new string(decrypt).ToLower();
                if (plain.Contains(" the ")) // http://www.world-english.org/english500.htm
                {
                    //Console.Write(new string(key.ToArray<char>()));
                    return decrypt.Select(c => (long)c).Sum();
                }
            }
            return 0;
        }
    }
}
